package com.ruoyi.web.controller.system;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.BydspecialPoject;
import com.ruoyi.system.domain.MaterialCutting.LaserModule;
import com.ruoyi.system.domain.MaterialCutting.LayoutModule;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.BydspecialPojectMapper;
import com.ruoyi.system.mapper.LaserModuleMapper;
import com.ruoyi.system.mapper.LayoutModuleMapper;
import com.ruoyi.system.service.BydspecialPojectService;
//import com.ruoyi.system.service.FileService;
import com.ruoyi.system.utils.ExcelDownUtils;
import com.ruoyi.system.utils.ExcelImporterUtils;

import com.ruoyi.system.utils.PdfUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import lombok.experimental.Wither;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;

@RestController
@RequestMapping("/bydspecialPoject")
public class BydspecialPojectController extends BaseController {
    @Autowired
    private BydspecialPojectMapper bydspecialPojectMapper;
    @Autowired
    private BydspecialPojectService bydspecialPojectService;

    @Autowired
    private LaserModuleMapper laserModuleMapper;
    @Autowired
    private LayoutModuleMapper layoutModuleMapper;
//    @Autowired
//    private FileService fileService;


    /**
     * 查询数据列表
     *
     * @param specialPojectDto
     * @return
     */
    @PostMapping("/selectBydspecialPojectList")
    public TableDataInfo selectBydspecialPojectList(@RequestBody BydSpecialPojectDto specialPojectDto) {
        startPage();
        List<BydspecialPoject> bydspecialPojects = bydspecialPojectMapper.selectBydspecialPojectList(specialPojectDto);
        return getDataTable(bydspecialPojects);
    }



    /**
     * Excel批量导入数据
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R uploadExcel(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return R.fail("文件为空");
        }

        try {
            List<BydspecialPoject> userList = ExcelImporterUtils.parseExcel(file);
            int count = bydspecialPojectMapper.batchList(userList);
            return R.ok("成功导入 " + count + " 条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入失败: " + e.getMessage());
        }
    }

    /**
     * 手动插入数据
     *
     * @param insertBydSpecialPojectDto
     * @return
     */

    @PostMapping("/insertData")
    public R insertData(@RequestBody InsertBydSpecialPojectDto insertBydSpecialPojectDto) {
        return bydspecialPojectService.insertData(insertBydSpecialPojectDto);
    }

    /**
     * 更改数据
     *
     * @param updateBydSpecialPojectDto
     * @return
     */
    @PostMapping("/updateData")
    public R updateData(@RequestBody UpdateBydSpecialPojectDto updateBydSpecialPojectDto) {
        return bydspecialPojectService.upadteData(updateBydSpecialPojectDto);
    }

    /**
     * 删除数据
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteId")
    public R deleteById(@RequestBody List<Long> id) {
        if (bydspecialPojectMapper.deleteByid(id)) {
            return R.ok("删除成功");
        }
        return R.fail("删除失败，请联系管理员处理");
    }

    @PostMapping("/downExcel")
    public void export(HttpServletResponse response,  BydSpecialPojectDto bydspecialPojects) {
        List<SelectBydSpecialPojectDto> bydSpecialPojectDtos = bydspecialPojectService.selectList(bydspecialPojects);
        ExcelUtil<SelectBydSpecialPojectDto> util = new ExcelUtil<SelectBydSpecialPojectDto>(SelectBydSpecialPojectDto.class);
        util.exportExcel(response, bydSpecialPojectDtos, "订单数据");
    }
    @PostMapping("/get")
    public void getmes(){
           String ACCESS_KEY_ID = "LTAI5tR9QDihYngU71Xwy6c2";     // 替换为你的AccessKey ID
           String ACCESS_KEY_SECRET = "tel3AbjTideHz7xvwI2VAlP9uRnfBo"; // 替换为你的AccessKey Secret

        // 短信签名和模板信息
           String SIGN_NAME = "你的短信签名";           // 替换为你的短信签名
           String TEMPLATE_CODE = "SMS_123456789";
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",          // 地域ID，短信服务一般为cn-hangzhou
                ACCESS_KEY_ID,
                ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers("13800138000");       // 接收短信的手机号码
        request.setSignName(SIGN_NAME);
        request.setTemplateCode(TEMPLATE_CODE);
        request.setTemplateParam("{\"code\":\"123456\"}");  // 模板参数，根据模板要求设置

        try {
            // 发送短信
            SendSmsResponse response = client.getAcsResponse(request);

            // 处理响应
            if ("OK".equals(response.getCode())) {
                System.out.println("短信发送成功！");
                System.out.println("RequestId: " + response.getRequestId());
                System.out.println("BizId: " + response.getBizId());
            } else {
                System.out.println("短信发送失败！");
                System.out.println("错误码: " + response.getCode());
                System.out.println("错误信息: " + response.getMessage());
            }
        } catch (ClientException e) {
            System.err.println("发送短信异常：" + e.getErrMsg());
            e.printStackTrace();
        }
    }

    @GetMapping("/selectById")
    public BydspecialPoject selectById(@RequestParam Long id){
        BydspecialPoject bydspecialPoject = bydspecialPojectMapper.selectById(id);
        if (bydspecialPoject.getProductPath()!=null){
            String path = bydspecialPoject.getProductPath().replace("\\","/").replace("C:/Users/旺仔爱~1/AppData/Local/Temp/","http://localhost:8080/static-pdfs/");
            bydspecialPoject.setProductPath(path);
        }

        return bydspecialPoject;
    }

//    @PostMapping("/processPdf")
//    public ResponseEntity<?> processPdf(@RequestParam("file") MultipartFile file) {
//        if (file.isEmpty()) {
//            return ResponseEntity.badRequest().body("没有选择文件");
//        }
//
//        if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
//            return ResponseEntity.badRequest().body("不允许的文件类型，只允许PDF");
//        }
//        String originalFilename = file.getOriginalFilename();
//        // 提取文件名前缀
//        String fileNamePrefix = PdfUtils.extractFileNamePrefix(originalFilename);
//        String numbers = fileNamePrefix.replaceAll("[^0-9]", "");
//        List<String> strings = bydspecialPojectService.selectModelByOrder(numbers);
//        try {
//            PdfProcessingResult result = PdfUtils.processPdf(file,strings);
//            return ResponseEntity.ok(result);
//        } catch (IOException e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("处理PDF时出错: " + e.getMessage());
//        }
//    }
//    @GetMapping("/download/{fileName:.+}")
//    public ResponseEntity<?> downloadFile(@PathVariable String fileName) {
//        try {
//            byte[] fileContent = PdfUtils.getProcessedFile(fileName);
//            if (fileContent == null) {
//                return ResponseEntity.notFound().build();
//            }
//
//            return ResponseEntity.ok()
//                    .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
//                    .contentType(MediaType.APPLICATION_PDF)
//                    .body(fileContent);
//        } catch (IOException e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("下载文件时出错: " + e.getMessage());
//        }
//    }
//
//    @PostMapping("/checkPage")
//    public ResponseEntity<Map<String, Object>> checkPDFByPage(
//            @RequestParam("file") MultipartFile pdfFile) {
//        Map<String, Object> result = new HashMap<>();
//        String originalFilename = pdfFile.getOriginalFilename();
//
//        // 提取文件名前缀
//        String fileNamePrefix = PdfUtils.extractFileNamePrefix(originalFilename);
//        String numbers = fileNamePrefix.replaceAll("[^0-9]", "");
//        List<String> strings = bydspecialPojectService.selectModelByOrder(numbers);
//        try {
//            // 保存临时文件
//            File tempFile = fileService.saveTempFile(pdfFile);
//
//            // 逐页检查PDF
//            PdfUtils.CheckResult checkResult = PdfUtils.checkPDFByPage(tempFile, strings);
//            result.put("containsText", checkResult.isContainsText());
//            result.put("matchedPages", checkResult.getMatchedPages());
//            result.put("fileName", pdfFile.getOriginalFilename());
//
//            // 根据检查结果保存文件
//            File savedFile = fileService.savePDFIfNeeded(tempFile, checkResult);
//            if (savedFile != null) {
//                result.put("savedPath", savedFile.getAbsolutePath());
//                result.put("saveDecision", "保存文件：存在匹配页后出现不匹配页");
//            } else {
//                result.put("saveDecision", "未保存：所有页都匹配或都不匹配");
//            }
//
//            // 删除临时文件
//            tempFile.delete();
//
//            return ResponseEntity.ok(result);
//        } catch (IOException e) {
//            result.put("error", "处理PDF时出错: " + e.getMessage());
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
//        }
//    }
}
